import React, { useEffect, useState } from "react";
import {
  PageHeader,
  IssuesItem,
  AddIssueBtn,
  Recommend,
  ScoreRank,
  TypeSelect,
} from "@/components";
import { getIssueByPage } from "@/api/issue";
import * as styles from "./issues.module.scss";
import { Empty, Pagination } from "antd";
import { useSelector } from "react-redux";

export default function Issues() {
  const [issueInfo, setIssueInfo] = useState([]);
  const [pageInfo, setPageInfo] = useState({
    current: 1, // 当前页码
    pageSize: 15, // 每页显示 15 条数据
    total: 0, // 数据的总条数
  });
  const { issueTypeId } = useSelector((state) => state.type);

  useEffect(() => {
    async function fecthData() {
      let searchParams = {
        current: pageInfo.current,
        pageSize: pageInfo.pageSize,
        issueStatus: true,
      };

      if (issueTypeId !== "all") {
        // 用户点击了分类的，那么就需要根据分类来渲染
        searchParams.typeId = issueTypeId;
        // 如果按照分类来进行查询，需要重新将当前页设置为第一页
        searchParams.current = 1;
      }

      const { data } = await getIssueByPage(searchParams);
      setIssueInfo(data.data);
      setPageInfo({
        current: data.currentPage,
        pageSize: data.eachPage,
        total: data.count,
      });
    }

    fecthData();
  }, [pageInfo.current, pageInfo.pageSize, issueTypeId]);

  let issuesList = [];
  for (let i = 0; i < issueInfo.length; i++) {
    issuesList.push(<IssuesItem key={i} issueInfo={issueInfo[i]} />);
  }

  const handlePageChange = (current, pageSize) => {
    setPageInfo({
      current,
      pageSize,
    });
  };

  return (
    <>
      <div className={styles.container}>
        <PageHeader title="问答列表">
          <TypeSelect />
        </PageHeader>
        <div className={styles.issueContainer}>
          {/* 左边区域 */}
          {issueInfo.length > 0 ? (
            <div className={styles.leftSide}>
              {issuesList}
              <div className="paginationContainer">
                <Pagination
                  showQuickJumper
                  defaultCurrent={1}
                  {...pageInfo}
                  onChange={handlePageChange}
                />
              </div>
            </div>
          ) : (
            <Empty style={{ margin: "10px auto" }} />
          )}
          {/* 右边区域 */}
          <div className={styles.rightSide}>
            <AddIssueBtn />
            <Recommend />
            <div style={{ marginTop: "30px" }}>
              <ScoreRank />
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
